package com.yicong.ants.ui.video;

import android.app.Activity;
import android.content.res.Resources;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;

import com.cchao.simplelib.core.CollectionHelper;
import com.cchao.simplelib.core.RxBus;
import com.cchao.simplelib.core.RxHelper;
import com.cchao.simplelib.core.UiHelper;
import com.cchao.simplelib.ui.adapter.StatefulBindMultiQuickAdapter;
import com.cchao.simplelib.util.StringHelper;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.yicong.ants.BR;
import com.yicong.ants.Constants;
import com.yicong.ants.R;
import com.yicong.ants.bean.common.MultiItemWrapper;
import com.yicong.ants.bean.video.CommitL1;
import com.yicong.ants.bean.video.CommitL2;
import com.yicong.ants.bean.video.VideoListBean;
import com.yicong.ants.databinding.DialogCommentSheetBinding;
import com.yicong.ants.manager.UserManager;
import com.yicong.ants.manager.http.RetrofitHelper;
import com.yicong.ants.ui.video.manager.SoftKeyBoardListener;
import com.yicong.ants.ui.video.widget.InputTextMsgDialog;
import com.yicong.ants.utils.RecyclerViewUtil;
import com.yicong.ants.utils.TimeHelper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.disposables.CompositeDisposable;

/**
 * @author LinDingQiang
 * @description
 * @time 4/24/21 1:41 PM
 * @email dingqiang.l
 */
public class CommentDialog {
    BottomSheetDialog mDialog;
    private Activity mContext;
    private InputTextMsgDialog inputTextMsgDialog;
    float mSlideOffset = 0;
    StatefulBindMultiQuickAdapter<MultiItemWrapper> mAdapter;
    static RecyclerView mRecyclerView;
    private int offsetY;
    private static RecyclerViewUtil mRecyclerViewUtil;
    private SoftKeyBoardListener mKeyBoardListener;
    static CompositeDisposable mDisposable;
    static String mVid;
    int page = 1;
    VideoListBean mVideoListBean;
    public static final int L_1 = 1;
    public static final int L_2 = 2;

    public CommentDialog(Activity context, CompositeDisposable disposable, VideoListBean videoListBean) {
        mContext = context;
        mDisposable = disposable;
        mVid = videoListBean.getVid();
        mVideoListBean = videoListBean;
        mRecyclerViewUtil = new RecyclerViewUtil();
        close();
        initView();
        initListener();
        loadPage(1);
    }

    private void initView() {
        if (mDialog != null) {
            return;
        }

        //view
        DialogCommentSheetBinding binding = DataBindingUtil.inflate(LayoutInflater.from(mContext), R.layout.dialog_comment_sheet, null, false);
        mRecyclerView = binding.recycler;
        binding.tvCommentCount.setText(mVideoListBean.getComment_qty() + " 条评论");
        binding.setClick(v -> {
            switch (v.getId()) {
                case R.id.close:
                    mDialog.dismiss();
                    close();
                    break;
                case R.id.rl_comment:
                    initInputTextMsgDialog(null, false, null);
                    break;
            }
        });
        //adapter
        initAdapter();
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        closeDefaultAnimator(mRecyclerView);

        mRecyclerView.setAdapter(mAdapter);
        mAdapter.disableLoadMoreIfNotFullPage();

        //dialog
        mDialog = new BottomSheetDialog(mContext, R.style.dialog);
        mDialog.setContentView(binding.getRoot());
        mDialog.setCanceledOnTouchOutside(true);
        BottomSheetBehavior<View> mDialogBehavior = BottomSheetBehavior.from((View) binding.getRoot().getParent());
        mDialogBehavior.setPeekHeight(getWindowHeight());
        mDialogBehavior.addBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
            @Override
            public void onStateChanged(@NonNull View bottomSheet, int newState) {
                if (newState == BottomSheetBehavior.STATE_HIDDEN) {
                    mDialogBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
                    return;
                }
                if (newState == BottomSheetBehavior.STATE_SETTLING) {
                    if (mSlideOffset <= -0.28) {
                        //当向下滑动时 值为负数
                        mDialog.dismiss();
                        close();
                    }
                }
            }

            @Override
            public void onSlide(@NonNull View bottomSheet, float slideOffset) {
                mSlideOffset = slideOffset;//记录滑动值
            }
        });
    }


    private void initAdapter() {
        mAdapter = new StatefulBindMultiQuickAdapter<MultiItemWrapper>(null) {
            @Override
            public Map<Integer, Integer> getTypeLayoutMap() {
                Map<Integer, Integer> map = new HashMap<>(8);
                map.put(L_1, R.layout.video_comment_level_1);
                map.put(L_2, R.layout.video_comment_level_2);
                return map;
            }

            @Override
            protected void convert(DataBindViewHolder helper, MultiItemWrapper data) {
                helper.getBinding().setVariable(BR.bean, data.getObject());
                switch (helper.getItemViewType()) {
                    case L_1: // 一级
                        helper.getBinding().setVariable(BR.click, (View.OnClickListener) v -> {
                            switch (v.getId()) {
                                case R.id.root:
                                    initInputTextMsgDialog((View) v.getParent(), true, data);
                                    break;
                                case R.id.like:
                                    CommitL1 bean = (CommitL1) data.getObject();
                                    if (UserManager.notLogin()) {
                                        UiHelper.showToast("请先登录");
                                        return;
                                    }
                                    mDisposable.add(RetrofitHelper.getApis()
                                        .videoCommentLike(bean.getComment_id())
                                        .compose(RxHelper.toMain())
                                        .subscribe(respBean -> {
                                            bean.setLike(bean.getLike() + (bean.is_like() ? -1 : 1));
                                            bean.set_like(!bean.is_like());
                                            mAdapter.notifyItemChanged(getData().indexOf(data));
                                        }, RxHelper.getErrorConsumer()));
                                    break;
                                case R.id.more:
                                    //在项目中是从服务器获取数据，其实就是二级评论分页获取
                                    final Map<String, String> params = new HashMap<>();
                                    params.put("comment_id", String.valueOf(((CommitL1) data.getObject()).getComment_id()));
                                    mDisposable.add(RetrofitHelper.getApis()
                                        .getVideoCommentReply(params)
                                        .compose(RxHelper.toMain())
                                        .subscribe(respBean -> {
                                            if (respBean.isCodeFail()) {
                                                UiHelper.showToast(respBean.getMsg());
                                                return;
                                            }
                                            List<MultiItemWrapper> list = new ArrayList<>();
                                            for (int i = 0; i < respBean.getData().size(); i++) {
                                                list.add(MultiItemWrapper.of(L_2, respBean.getData().get(i)));
                                            }
                                            mAdapter.addData(getData().indexOf(data) + 1, list);
                                            UiHelper.setVisibleElseGone(v, false);
                                        }, RxHelper.getErrorConsumer()));

                                    break;
                            }
                        });
                        break;
                    case L_2: // 二级
                        helper.getBinding().setVariable(BR.click, (View.OnClickListener) v -> {
                            switch (v.getId()) {
                                case R.id.root:
                                    initInputTextMsgDialog((View) v.getParent(), true, data);
                                    break;
                                case R.id.like:
                                    //二级评论点赞 项目中还得通知服务器 成功才可以修改
                                    CommitL2 bean = (CommitL2) data.getObject();
                                    mDisposable.add(RetrofitHelper.getApis()
                                        .videoCommentLike(bean.getComment_id())
                                        .compose(RxHelper.toMain())
                                        .subscribe(respBean -> {
                                            bean.setLike(bean.getLike() + (bean.is_like() ? -1 : 1));
                                            bean.set_like(!bean.is_like());
                                            mAdapter.notifyItemChanged(getData().indexOf(data));
                                        }, RxHelper.getErrorConsumer()));
                            }
                        });
                        break;
                }
            }

            @Override
            public void loadPageData(int page) {
                loadPage(page);
            }

        };
        mAdapter.bindToRecyclerView(mRecyclerView);
        mAdapter.setOnLoadMoreListener(() -> {
            page++;
            loadPage(page);
        }, mRecyclerView);
    }

    private void initListener() {
        //滚动事件
        if (mRecyclerViewUtil != null) {
            mRecyclerViewUtil.initScrollListener(mRecyclerView);
        }

        mKeyBoardListener = new SoftKeyBoardListener(mContext, new SoftKeyBoardListener.OnSoftKeyBoardChangeListener() {
            @Override
            public void keyBoardShow(int height) {
            }

            @Override
            public void keyBoardHide(int height) {
                dismissInputDialog();
            }
        });
    }

    void initInputTextMsgDialog(View view, final boolean isReply, final MultiItemWrapper item) {
        dismissInputDialog();
        if (view != null) {
            offsetY = view.getTop();
            scrollLocation(offsetY);
        }
        if (inputTextMsgDialog == null) {
            inputTextMsgDialog = new InputTextMsgDialog(mContext, R.style.dialog);

            if (item != null) {
                String be_commenter = null;
                if (item.getItemType() == L_2) {
                    be_commenter = ((CommitL2) item.getObject()).getNickname();
                } else {
                    be_commenter = ((CommitL1) item.getObject()).getNickname();
                }
                inputTextMsgDialog.setHint("回复 " + be_commenter);
            }

            inputTextMsgDialog.setmOnTextSendListener(new InputTextMsgDialog.OnTextSendListener() {
                @Override
                public void onTextSend(String content) {
                    String commentId = "";
                    if (item != null) {
                        if (item.getItemType() == L_1) {
                            commentId = ((CommitL1) item.getObject()).getComment_id();
                        } else if (item.getItemType() == L_2) {
                            commentId = ((CommitL2) item.getObject()).getComment_id();
                        }

                        if (StringHelper.isEmpty(commentId)) {
                            UiHelper.showToast("评论异常");
                        }
                    }

                    Map<String, String> map1 = new HashMap<>();
                    map1.put("vid", mVid);
                    map1.put("content", content);
                    map1.put("comment_id", String.valueOf(commentId));
                    mDisposable.add(RetrofitHelper.getApis()
                        .videoComment(map1)
                        .compose(RxHelper.toMain())
                        .subscribe(respBean -> {
                            UiHelper.showToast(respBean.getMsg());
                            if (respBean.isCodeFail()) {
                                return;
                            }
                            addComment(isReply, item, respBean.getData().getComment_id(), content);
                        }, RxHelper.getErrorConsumer()));
                }

                @Override
                public void dismiss() {
                    //item滑动到原位
                    scrollLocation(-offsetY);
                }
            });
        }
        inputTextMsgDialog.show();
    }

    void addComment(boolean isReply, MultiItemWrapper item, String comment_id, String content) {
        String userName = UserManager.getUserBean().getNickname();
        String avatar = UserManager.getUserBean().getAvatar();
        String createTime = TimeHelper.formatCurTime("yyyy-MM-dd HH:mm:ss");
        String be_commenter = "";
        if (item != null && isReply) {
            if (item.getItemType() == L_2) {
                be_commenter = ((CommitL2) item.getObject()).getNickname();
            } else {
                be_commenter = ((CommitL1) item.getObject()).getNickname();
            }
        }
        if (isReply) {
/*           mRecyclerView.postDelayed(() -> ((LinearLayoutManager) mRecyclerView.getLayoutManager())
                .scrollToPositionWithOffset(Math.min(positionCount, data.size() - 1), positionCount >= data.size() - 1 ? Integer.MIN_VALUE : mRecyclerView.getHeight()), 100);
*/
            CommitL2 commit = new CommitL2()
                .setAvatar(avatar)
                .setNickname(userName)
                .setComment_id(comment_id)
                .setBe_commenter(be_commenter)
                .setContent(content)
                .setCreated_at(createTime);
            mAdapter.addData(mAdapter.getData().indexOf(item) + 1, MultiItemWrapper.of(L_2, commit));
        } else {
            CommitL1 commitL1 = new CommitL1()
                .setAvatar(avatar)
                .setNickname(userName)
                .setComment_id(comment_id)
                .setContent(content)
                .setCreated_at(createTime);

            mAdapter.addData(0, MultiItemWrapper.of(L_1, commitL1));
            mRecyclerView.scrollToPosition(0);
        }
        mAdapter.loadMoreEnd();
        RxBus.get().postEvent(Constants.Event.Video_Commit_Suc, mVid);
    }

    private void dismissInputDialog() {
        if (inputTextMsgDialog != null) {
            if (inputTextMsgDialog.isShowing()) inputTextMsgDialog.dismiss();
            inputTextMsgDialog.cancel();
            inputTextMsgDialog = null;
        }
    }

    private int getWindowHeight() {
        Resources res = mContext.getResources();
        DisplayMetrics displayMetrics = res.getDisplayMetrics();
        return displayMetrics.heightPixels;
    }

    // item滑动
    public void scrollLocation(int offsetY) {
        try {
            mRecyclerView.smoothScrollBy(0, offsetY);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 关闭默认局部刷新动画
     */
    public void closeDefaultAnimator(RecyclerView mRvCustomer) {
        if (null == mRvCustomer) return;
        mRvCustomer.getItemAnimator().setAddDuration(0);
        mRvCustomer.getItemAnimator().setChangeDuration(0);
        mRvCustomer.getItemAnimator().setMoveDuration(0);
        mRvCustomer.getItemAnimator().setRemoveDuration(0);
        ((SimpleItemAnimator) mRvCustomer.getItemAnimator()).setSupportsChangeAnimations(false);
    }

    //原始数据 一般是从服务器接口请求过来的
    void loadPage(int page) {
        final Map<String, String> params = new HashMap<>();
        params.put("page", String.valueOf(page));
        params.put("page_size", String.valueOf(Constants.PAGE_SIZE));
        params.put("vid", mVid);
        mDisposable.add(RetrofitHelper.getApis()
            .getVideoCommentList(params)
            .compose(RxHelper.toMain())
            .subscribe(respBean -> {
                if (respBean.isCodeFail()) {
                    UiHelper.showToast(respBean.getMsg());
                    return;
                }

                List<MultiItemWrapper> list = new ArrayList<>();
                if (CollectionHelper.isNotEmpty(respBean.getData())) {
                    for (CommitL1 commitL1 : respBean.getData()) {
                        list.add(MultiItemWrapper.of(L_1, commitL1));
                    }
                }
                mAdapter.solvePagesData(list, page, Constants.PAGE_SIZE);
            }, RxHelper.getSwitchableErrorConsumer(mAdapter)));
    }

    public void show() {
        mSlideOffset = 0;
        mDialog.show();
    }

    public void close() {
        if (mRecyclerViewUtil != null) {
            mRecyclerViewUtil.destroy();
            mRecyclerViewUtil = null;
        }
        if (mKeyBoardListener != null) {
            mKeyBoardListener.setOnSoftKeyBoardChangeListener(null);
            mKeyBoardListener = null;
        }
        mAdapter = null;
    }

}
